package cn.cd.anStudio;

import cn.cd.anStudio.io.MyBusNetUtil;
import cn.cd.anStudio.util.MyBusCommonUtil;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyBusLocationService extends Service {
	
	private static final String TAG = "MyBusLocationService";
	
	private String key       = null;
	private String busNum    = null;
	private String busStop   = null;
	private int    queryType = -1;

	@Override
	public IBinder onBind(Intent intent) {
		
		Log.v(TAG, "Bind service");

		return null;
	}
	
	private void alertUserByAlarm(int alerttype) {
		
		AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		
		Intent intentToFire = new Intent("com.cn.cd.anstudio.receiver.MYBUSLOCATION");
		intentToFire.putExtra("type", alerttype);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
		alarms.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
		
		this.stopSelf();
	}

	 @Override
	 public void onCreate() {
		 super.onCreate();
		 
		 Log.v(TAG, "Service Created");
	 }
	 
	 @Override
	 public void onStart(Intent intent, int startId) {
		 
		 Log.v(TAG, "Service Started");
		 
		 key       = intent.getStringExtra("keyWord");
		 busNum    = intent.getStringExtra("busNum");
		 busStop   = intent.getStringExtra("busStop");
		 queryType = intent.getIntExtra("queryType", 0);
		 
		 final int userKey = Integer.parseInt(key);
		 
		 new Thread(new Runnable() {

				public void run() {
					while(true) {
						try {
							Log.v(TAG, "Service is running");
		                    
		                    MyBusNetUtil myNetUtil = new MyBusNetUtil();
		                    int queryKey = myNetUtil.getBusDistanceToStop(busNum, busStop, queryType);
		                    
		                    Log.v(TAG, "Get queried key " + queryKey);
		                    
		                    if (queryKey <= 0) {
		                    	alertUserByAlarm(MyBusCommonBase.LOCATION_SERVICE_ERROR);
		                        return;
		                    }

		                    if (queryKey == userKey) {
		                    	alertUserByAlarm(MyBusCommonBase.LOCATION_SERVICE_ARRIVE);
		                    	return;
		                    }
		                    
		                    //To cut off redundant network task, query period is scheduled here
		                    Thread.sleep(MyBusCommonUtil.scheduleQueryInterInMilliSecond(queryKey - userKey));
		                } catch (InterruptedException e) {
		                }
					}
	            }
			 }).start();
	 }
	 
	 @Override
	 public void onDestroy() {
		 super.onDestroy();
		 Log.v(TAG, "Service Destroyed");
	 }

}
